package com.yonyou.brigade.cron.order.ctripBC;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.model.Developer;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.service.IDeveloperService;
import com.yonyou.brigade.third_parties.ctripBC.model.CtripBCConfig;
import com.yonyou.brigade.third_parties.ctripBC.service.ICtripBCOrderService;
import com.yonyou.brigade.util.operateutil.DateUtils;
import com.yonyou.ybzboot.starter.elasticjob.lite.annotation.ElasticJobConfig;
import com.yonyou.ybzboot.starter.mail.model.Email;
import com.yonyou.ybzboot.starter.mail.service.IMailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Handler;

/**
 * 携程（大客户）订单定时拉取任务
 *
 * @Auther: kangfw5@yonyou.com
 * @Date: 2019/1/8 10:18
 */
@ElasticJobConfig(cron = "0 10 2 * * ? ", shardingTotalCount = 1)
@Component
public class FetchCtripBCOrders implements SimpleJob {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    @Qualifier("briChannelServiceImpl")
    private IBriChannelService briChannelService;

    @Autowired
    @Qualifier("ctripBCOrderServiceImpl")
    private ICtripBCOrderService ctripBCOrderService;

    @Autowired
    @Qualifier("developerServiceImpl")
    private IDeveloperService developerService;

    @Autowired
    private IMailService mailService;

    @Value("${brigade.cur}")
    private String curEnv;

    @Override
    public void execute(ShardingContext shardingContext) {
        log.info("<<<<ctrip-bc-pull-orders-begin>>>>");
        List<BriChannel> briChannels = briChannelService.getEnableChannelByChannel(ChannelEnum.CTRIPBC.getName());
        Set<String> configs = new HashSet<>();
        if (briChannels != null && briChannels.size() > 0) {
            List<String> channelConfigList = new ArrayList<>();
            for (BriChannel briChannel : briChannels) {
                //防止重复拉单
                if(!configs.add(briChannel.getConfig())) {
                    continue;
                }
                CtripBCConfig config  = JSONObject.parseObject(briChannel.getConfig(), CtripBCConfig.class);
                if (channelConfigList.contains(config.getAppKey())){
                    continue;
                } else {
                    channelConfigList.add(config.getAppKey());
                }
                String tenant = briChannel.getTenant();
                String orgpk = briChannel.getOrgpk();
                String begin = DateUtils.getCurrentDateMinusOneDay();
//                String end = DateUtils.getCurrentDateMinusOneDay();
                // modify by yangxw1 2021年7月14日 定时任务执行是时间不能是同一天
                String end = DateUtils.getCurrentDateDay();
                try {
                    if ("1".equals(config.getOrderGetMod())) {
                        //拉取结算数据
                        ctripBCOrderService.getCtripBCFlightSettleOrders(tenant, orgpk, begin, end, briChannel.getId(), config);
                        ctripBCOrderService.getCtripBCHotelSettleOrders(tenant, orgpk, begin, end, briChannel.getId(), config);
                        ctripBCOrderService.getCtripBCTrainSettleOrders(tenant, orgpk, begin, end, briChannel.getId(), config);
                        ctripBCOrderService.getCtripBCCarSettleOrders(tenant, orgpk, begin, end, briChannel.getId(), config);
                    } else {
                        //拉取订单数据
                        ctripBCOrderService.getCtripBCOrders(tenant, orgpk, begin, end, briChannel.getId(), config);
                    }
                } catch (Exception e) {
                    Wrapper<Developer> developerWrapper = new EntityWrapper<>();
                    developerWrapper.where("type={0}", "KF");
                    List<Developer> developers = developerService.selectList(developerWrapper);
                    String developerEmails = "";
                    for (int j = 0; j < developers.size(); j++) {
                        developerEmails += developers.get(j).getEmail();
                        if (j < developers.size() - 1) {
                            developerEmails += ",";
                        }
                    }
                    Email email = new Email();
                    String[] emails = developerEmails.split(",");
                    email.setEmail(emails);
                    email.setSubject(curEnv + "环境携程（大客户）拉单失败");
                    email.setContent(e.getMessage());
                    try {
                        log.error(e.getMessage());
                        mailService.send(email);
                    } catch (Exception e1) {
                        log.error("提示" + curEnv + "环境携程订（大客户）单拉单失败的邮件发送失败！" + e1.getMessage());
                    }
                }
            }
        }
        configs=null;
        log.info("<<<<ctrip-bc-pull-orders-end>>>>");
    }
}